//
//  SearchFriendsViewController.m
//  CandyCrushClone
//
//  Created by Petar on 2/22/15.
//  Copyright (c) 2015 Nestorov Engineering. All rights reserved.
//

#import "SearchFriendsViewController.h"
#import "Globals.h"
#import "CommunicationManager.h"
#import "SearchResultCell.h"

static NSString * const SearchResultCellIdentifier = @"SearchResultCell";
static NSString * const NothingFoundCellIdentifier = @"NothingFoundCell";
static NSString * const LoadingCellIdentifier = @"LoadingCell";

@interface SearchFriendsViewController () <SearchResultCellDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation SearchFriendsViewController
{
    
    NSMutableArray *_buddyListNames;
    NSString *_myUsername;
    NSArray *_searchResults;
    BOOL _isSearching;
    CommunicationManager *_communicationManager;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    UINib *cellNib = [UINib nibWithNibName:SearchResultCellIdentifier bundle:nil];
    [_tableView registerNib:cellNib forCellReuseIdentifier:SearchResultCellIdentifier];
    
    _communicationManager = [CommunicationManager sharedManager];
    
    _buddyListNames = [NSMutableArray new];
    NSArray *buddyList = [_communicationManager getBuddyList];
    
    // Make list with names of all my buddies
    for (SFSBuddy *buddy in buddyList) {
        [_buddyListNames addObject:buddy.name];
    }
    
    // store my username for later usage
    _myUsername = [_communicationManager getMyUsername];
    
    // Listen for UPDATE_LIST_OF_USERS from CommunicationManager
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSearchResults:)  name:UPDATE_LIST_OF_USERS object:nil];
    
}


- (void)updateSearchResults:(NSNotification *)notification
{
    
    // The searching is done.
    _isSearching = NO;
    
    NSDictionary *userInfo = notification.userInfo;
    NSArray *listOfUsers = userInfo[@"listOfUsers"];
    
    // Check for found usernames
    if ( listOfUsers != nil && [listOfUsers isKindOfClass:[NSArray class]] ) {
        _searchResults = listOfUsers;
    }
    
    // Refresh the TableView with the result
    [_tableView reloadData];
    
}


- (IBAction)didPressSearchButton:(id)sender
{
    
    // to hide the Keyboard
    [_textField resignFirstResponder];
    
    // Do NOT search for less than 3 symbols
    if ( _textField.text == nil || _textField.text.length < 3 ) {
        NSLog(@"Do NOT search because _textField.text is less than 3 symbols.");
        return;
    }
    
    _searchResults = [NSArray new];
    _isSearching = YES;
    
     // to show LoadingCell
    [_tableView reloadData];
    
    // getList with usernames from Server
    [_communicationManager getListOfUsersForName:_textField.text];
    
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if ( _searchResults == nil ) {
        return 0; // Not searched yet
        
    } else if ( _isSearching == YES ) {
        return 1; // Loading...
        
    } else if ( [_searchResults count] == 0 ) {
        return 1; // Nothing Found
        
    } else {
        return [_searchResults count];
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ( _isSearching == YES ) {
        
        // Show LoadingCell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LoadingCellIdentifier forIndexPath:indexPath];
        UIActivityIndicatorView *spinner = (UIActivityIndicatorView *)[cell viewWithTag:100];
        [spinner startAnimating];
        
        return cell;
        
    } else if ( [_searchResults count] == 0 ) {
        
        // Show NothingFoundCell
        return [tableView dequeueReusableCellWithIdentifier:NothingFoundCellIdentifier forIndexPath:indexPath];
        
    } else {
        
        SearchResultCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchResultCellIdentifier forIndexPath:indexPath];
        // Show SearchResultCell
        NSString *username = _searchResults[indexPath.row];
        
        [cell configureWithName:username andBuddyList:_buddyListNames andMyUsername:_myUsername forIndexPath:indexPath];
        cell.delegate = self;
        
        return cell;
    }
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [_textField resignFirstResponder];
}


#pragma mark - SearchResultCellDelegate methods
- (void)didPressAddButtonAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSLog(@"Pressed Row: %ld",(long)indexPath.row);
    NSLog(@"Selected username: %@",_searchResults[indexPath.row]);
    
    // Add it in temporary list with BuddyNames to hide 'Add' button
    [_buddyListNames addObject:_searchResults[indexPath.row]];
    
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    [_communicationManager inviteUserToBuddylist:_searchResults[indexPath.row]];
    
}


- (IBAction)didPressBackButton:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)didPressMenuButton:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (BOOL)prefersStatusBarHidden
{
    return YES;
}


// Remove Observer
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
